package com.inspinia.upms.server.controller.upms;

import com.inspinia.base.common.model.AjaxResult;
import com.inspinia.base.pagination.Pager;
import com.inspinia.base.util.CollectionUtil;
import com.inspinia.base.util.StringUtils;
import com.inspinia.upms.common.model.post.UpmsPost;
import com.inspinia.upms.common.model.post.UpmsPostVo;
import com.inspinia.upms.common.util.CacheClearUpUtil;
import com.inspinia.upms.rpc.api.UpmsPostService;
import com.inspinia.upms.rpc.api.UpmsUserService;
import com.inspinia.upms.server.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * 岗位信息操作处理
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/upms/post/")
public class UpmsPostController extends BaseController {
    private String prefix = "upms/post/";

    @Resource
    private UpmsPostService postService;

    @Resource
    private UpmsUserService upmsUserService;

    /**
     * 跳转分页页面
     *
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String toPaginationPage() {
        return prefix + "post-pagination";
    }


    /**
     * 分页查询
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public AjaxResult paging(UpmsPostVo postVo) throws InvocationTargetException, IllegalAccessException {
        Pager<UpmsPostVo> page = postService.findPage(postVo);
        return new AjaxResult(true, page);
    }

    /**
     * 跳转添加页面
     *
     * @return
     */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String goCreate() {
        return prefix+ "post-create";
    }

    /**
     * 创建Post
     *
     * @param post
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public AjaxResult create(@Valid UpmsPost post) {
        String realName = upmsUserService.getRealNameById(getPrincipalId());
        if (StringUtils.isNotBlank(realName)){
            post.setCreateBy(realName);
        }
        postService.insert(post);
        return new AjaxResult(true);
    }

    /**
     * 根据id获取Post
     *
     * @param id id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public AjaxResult get(long id) {
        UpmsPost bean = postService.get(id);
        return new AjaxResult(true, bean);
    }

    /**
     * 根据id获取Post
     *
     * @param id id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getVo", method = RequestMethod.GET)
    public AjaxResult getVo(long id) throws InvocationTargetException, IllegalAccessException {
        UpmsPostVo vo = postService.getVo(id);
        return new AjaxResult(true, vo);
    }

    /**
     * 编辑Post
     *
     * @param post
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public AjaxResult edit(@Valid UpmsPost post) {
        String realName = upmsUserService.getRealNameById(getPrincipalId());
        if (StringUtils.isNotBlank(realName)){
            post.setUpdateBy(realName);
        }
        postService.update(post);
        return new AjaxResult(true);
    }

    /**
     * 编辑
     *
     * @param postId
     * @return
     */
    @RequestMapping(value = "edit", method = RequestMethod.GET)
    public String toEdit(Long postId, Model model) throws InvocationTargetException, IllegalAccessException {
        UpmsPostVo vo = postService.getVo(postId);
        List<Long> resourceIds = postService.findResourceIds(postId);
        model.addAttribute("post",vo);
        if (CollectionUtil.isNotEmpty(resourceIds)){
            model.addAttribute("resourcesIds",CollectionUtil.list2string(resourceIds));
        }
        return prefix + "post-edit";
    }

    /**
     * 批量删除Post
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "batchDelete", method = RequestMethod.POST)
    public AjaxResult delete(@RequestParam(name = "ids[]") Long[] ids) {
        for (Long id : ids) {
            cleanUserPermissionCacheByPostId(id);
        }
        int i = postService.batchDelete(ids);
        if (i == ids.length) {
            return new AjaxResult(true);
        } else {
            return new AjaxResult(false, "有" + (ids.length - i) + "个岗位删除失败");
        }
    }

    /**
     * 获取岗位已分配的资源
     *
     * @param id 岗位id
     * @return
     */
    @ResponseBody
    @RequestMapping("findResourceIds")
    public List<Long> findResourceIds(Long id) {
        return postService.findResourceIds(id);
    }

    /**
     * 给岗位分配资源
     *
     * @param resourceIds 资源id集合
     * @param postId      岗位id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "setResources", method = RequestMethod.POST)
    public AjaxResult setResources(@RequestParam(name = "resourceIds[]", required = false) List<Long> resourceIds, Long postId) {

        int saved = postService.setResources(postId, resourceIds);
        if (CollectionUtil.isEmpty(resourceIds) || saved == resourceIds.size()) {
            cleanUserPermissionCacheByPostId(postId);
            return new AjaxResult(true);
        }
        return new AjaxResult(false, "有" + (resourceIds.size() - saved) + "个资源保存失败!");
    }

    /**
     * 清除岗位下所有用户的权限缓存
     *
     * @param postId 岗位id
     */
    private void cleanUserPermissionCacheByPostId(Long postId) {
        List<Long> userIds = postService.findUserIdsByPostId(postId);
        CacheClearUpUtil.cleanUserResourceCache(userIds);
    }

    /**
     * 根据部门id获取所有岗位
     *
     * @param deptId 部门id
     */
    @RequestMapping("findPostByDept")
    @ResponseBody
    public List<UpmsPost> findPostBydeptId(Long deptId) {
        return postService.findPostByDeptId(deptId);
    }

}
